<template>
  <view class="article-detail-container">
    <!-- 自定义页头 -->
    <CustomHeader ref="customHeader" :showBack="true" title="文章详情"></CustomHeader>
    
    <!-- 文章详情页头 -->
    <view class="article-header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <image
            class="back-icon"
            src="/static/icons/candidate/pre_page.png"
          ></image>
          <text class="back-text">返回</text>
        </view>
        <text class="header-title">文章详情</text>
        <view class="header-right"></view>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 文章内容 -->
    <view v-else-if="articleDetail" class="article-content-wrapper">
      <scroll-view 
        class="article-scroll" 
        scroll-y 
        :style="{ height: scrollHeight + 'px' }"
      >
        <view class="article-content">
          <!-- 文章标题 -->
          <view class="article-title-section">
            <text class="article-title">{{ articleDetail.title }}</text>
          </view>
          
          <!-- 作者信息 -->
          <view class="author-section">
            <image 
              :src="articleDetail.publisherFace || '/static/images/avatar.png'" 
              class="author-avatar"
            ></image>
            <view class="author-info">
              <text class="author-name">{{ articleDetail.publisher }}</text>
              <text class="publish-time">{{ formatPublishTime(articleDetail.publishTime) }}</text>
            </view>
          </view>
          
          <!-- 分割线 -->
          <view class="divider"></view>
          
          <!-- 文章正文 -->
          <view class="article-body">
            <mp-html 
              :content="articleDetail.contentHtml"
              @imgtap="previewImage"
              :show-img-menu="false"
              class="mp-html-content"
            ></mp-html>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 错误状态 -->
    <view v-else class="error-container">
      <image 
        src="/static/images/candidate/empty.png" 
        class="error-image"
      ></image>
      <text class="error-text">文章加载失败</text>
      <view class="retry-btn" @click="loadArticleDetail">
        <text class="retry-text">重新加载</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import CustomHeader from "@/components/CustomHeader.vue";
import mpHtml from "mp-html/dist/uni-app/components/mp-html/mp-html.vue";
import { getArticleDetailApi, addReadCountApi } from "@/api/article.js";

// 响应式数据
const articleDetail = ref(null);
const loading = ref(true);
const scrollHeight = ref(500);
const articleId = ref("");

// 页面加载时获取参数
onLoad((options) => {
  articleId.value = options.articleId || '';
  console.log("页面加载，获取到的文章ID:", articleId.value);
  
  if (articleId.value) {
    nextTick(() => {
      calculateScrollHeight();
      loadArticleDetail();
    });
  } else {
    console.error("未获取到文章ID");
    loading.value = false;
  }
});

// 计算滚动区域高度
const calculateScrollHeight = () => {
  try {
    const systemInfo = uni.getSystemInfoSync();
    console.log("系统信息:", systemInfo);

    // 计算可用高度：总高度 - CustomHeader高度 - 文章页头高度 - 安全区域
    const customHeaderHeight = uni.upx2px(88); // CustomHeader高度
    const articleHeaderHeight = uni.upx2px(88); // 文章详情页头高度
    const safeAreaBottom = systemInfo.safeAreaInsets?.bottom || 0;

    let availableHeight = systemInfo.windowHeight - customHeaderHeight - articleHeaderHeight - safeAreaBottom;

    // 确保最小高度
    availableHeight = Math.max(availableHeight, 300);

    scrollHeight.value = availableHeight;
    console.log(
      "计算的scroll-view高度:",
      scrollHeight.value,
      "原始窗口高度:",
      systemInfo.windowHeight
    );
  } catch (error) {
    console.error("计算滚动高度失败:", error);
    // 设置一个默认高度
    scrollHeight.value = 500;
  }
};

// 加载文章详情
const loadArticleDetail = async () => {
  if (!articleId.value) {
    console.error("文章ID为空");
    loading.value = false;
    return;
  }

  try {
    loading.value = true;
    console.log("开始加载文章详情，ID:", articleId.value);
    
    const res = await getArticleDetailApi(articleId.value);
    console.log("文章详情响应:", res);
    
    if (res) {
      articleDetail.value = res;
      console.log("文章详情加载成功");
      
      // 文章详情加载成功后，增加阅读数量（后台操作，不显示加载动画）
      addReadCount();
    } else {
      console.error("文章详情数据为空");
    }
  } catch (error) {
    console.error("获取文章详情失败:", error);
    uni.showToast({
      title: "获取文章详情失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 增加文章阅读数量
const addReadCount = async () => {
  if (!articleId.value) {
    console.error("文章ID为空，无法增加阅读数量");
    return;
  }

  try {
    console.log("增加文章阅读数量，ID:", articleId.value);
    await addReadCountApi(articleId.value);
    console.log("文章阅读数量增加成功");
  } catch (error) {
    console.error("增加文章阅读数量失败:", error);
    // 这里不显示错误提示，因为这是后台操作，不应该影响用户体验
  }
};

// 格式化发布时间
const formatPublishTime = (time) => {
  if (!time) return "";
  
  try {
    const publishDate = new Date(time);
    const now = new Date();
    const diffTime = now - publishDate;
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays === 0) {
      return "今天发布";
    } else if (diffDays === 1) {
      return "昨天发布";
    } else if (diffDays < 7) {
      return `${diffDays}天前发布`;
    } else {
      // 返回完整日期格式
      const year = publishDate.getFullYear();
      const month = publishDate.getMonth() + 1;
      const day = publishDate.getDate();
      return `${year}年${month}月${day}日发布`;
    }
  } catch (error) {
    console.error("时间格式化失败:", error);
    return time; // 返回原始时间
  }
};

// 图片预览功能
const previewImage = (e) => {
  console.log("图片预览事件:", e);
  
  // 获取点击的图片src
  const currentSrc = e.attrs?.src || e.src;
  
  if (!currentSrc) {
    console.error("未找到图片源地址");
    return;
  }
  
  // 从文章内容中提取所有图片URL
  const imageUrls = extractImageUrls(articleDetail.value?.contentHtml || "");
  
  console.log("当前图片:", currentSrc);
  console.log("所有图片:", imageUrls);
  
  // 使用uni.previewImage进行图片预览
  uni.previewImage({
    current: currentSrc,
    urls: imageUrls.length > 0 ? imageUrls : [currentSrc],
    success: () => {
      console.log("图片预览成功");
    },
    fail: (error) => {
      console.error("图片预览失败:", error);
    }
  });
};

// 从HTML内容中提取图片URL
const extractImageUrls = (htmlContent) => {
  if (!htmlContent) return [];
  
  const imageUrls = [];
  // 使用正则表达式匹配img标签的src属性
  const imgRegex = /<img[^>]+src=["|']([^"|']+)["|'][^>]*>/gi;
  let match;
  
  while ((match = imgRegex.exec(htmlContent)) !== null) {
    if (match[1]) {
      imageUrls.push(match[1]);
    }
  }
  
  return imageUrls;
};

// 返回上一页
const goBack = () => {
  uni.navigateBack({
    delta: 1,
    success: () => {
      console.log("返回成功");
    },
    fail: (error) => {
      console.error("返回失败:", error);
      // 如果返回失败，尝试跳转到发现页面
      uni.redirectTo({
        url: "/pages/candidate/discover"
      });
    }
  });
};
</script>

<style lang="less" scoped>
.article-detail-container {
  background-color: #ffffff;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 文章详情页头 */
.article-header {
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
  position: sticky;
  top: 88rpx; /* CustomHeader的高度 */
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 20rpx;
}

.back-btn {
  display: flex;
  align-items: center;
  padding: 10rpx 0;
  min-width: 120rpx;
}

.back-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 8rpx;
}

.back-text {
  font-size: 28rpx;
  color: #333333;
}

.header-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
  text-align: center;
  flex: 1;
}

.header-right {
  min-width: 120rpx;
}

/* 加载状态 */
.loading-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #999999;
}

/* 文章内容区域 */
.article-content-wrapper {
  flex: 1;
  overflow: hidden;
}

.article-scroll {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  /* 隐藏滚动条 */
  &::-webkit-scrollbar {
    display: none !important;
    width: 0 !important;
    height: 0 !important;
    background: transparent !important;
  }

  scrollbar-width: none !important; /* Firefox */
  -ms-overflow-style: none !important; /* IE 10+ */
}

.article-content {
  padding: 30rpx;
}

/* 文章标题区域 */
.article-title-section {
  margin-bottom: 30rpx;
}

.article-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
  line-height: 1.4;
  display: block;
}

/* 作者信息区域 */
.author-section {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.author-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.author-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.author-name {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.publish-time {
  font-size: 24rpx;
  color: #999999;
}

/* 分割线 */
.divider {
  height: 1rpx;
  background-color: #f0f0f0;
  margin-bottom: 40rpx;
}

/* 文章正文 */
.article-body {
  line-height: 1.8;
}

.mp-html-content {
  font-size: 28rpx;
  color: #333333;
  line-height: 1.8;
  width: 100%;
  max-width: 100%;
  overflow-x: hidden;
  box-sizing: border-box;
  
  /* mp-html组件样式 */
  :deep(.mp-html) {
    width: 100%;
    max-width: 100%;
    overflow-x: hidden;
    box-sizing: border-box;
    /* 段落样式 */
    p {
      margin-bottom: 20rpx;
      line-height: 1.8;
      color: #333333;
      word-wrap: break-word;
      word-break: break-all;
      max-width: 100%;
      overflow-wrap: break-word;
    }
    
    /* 标题样式 */
    h1 {
      font-size: 36rpx;
      font-weight: 600;
      color: #333333;
      margin: 40rpx 0 20rpx 0;
      padding-bottom: 10rpx;
      border-bottom: 2rpx solid #00bdb4;
      word-wrap: break-word;
      word-break: break-all;
      max-width: 100%;
      overflow-wrap: break-word;
    }
    
    h2 {
      font-size: 32rpx;
      font-weight: 600;
      color: #333333;
      margin: 35rpx 0 18rpx 0;
      padding-bottom: 8rpx;
      border-bottom: 1rpx solid #e0e0e0;
      word-wrap: break-word;
      word-break: break-all;
      max-width: 100%;
      overflow-wrap: break-word;
    }
    
    h3 {
      font-size: 30rpx;
      font-weight: 500;
      color: #333333;
      margin: 30rpx 0 15rpx 0;
      word-wrap: break-word;
      word-break: break-all;
      max-width: 100%;
      overflow-wrap: break-word;
    }
    
    /* 图片样式 */
    img {
      max-width: 100% !important;
      height: auto !important;
      border-radius: 8rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
      margin: 20rpx 0;
      display: block;
    }
    
    /* 代码块样式 */
    pre {
      background-color: #f8f8f8;
      border-radius: 8rpx;
      padding: 20rpx;
      margin: 20rpx 0;
      overflow-x: auto;
      max-width: 100%;
      width: 100%;
      box-sizing: border-box;
      white-space: pre;
      word-wrap: normal;
      border: 1rpx solid #e8e8e8;
      
      /* 美化滚动条 */
      &::-webkit-scrollbar {
        height: 8rpx;
      }
      
      &::-webkit-scrollbar-track {
        background-color: #f1f1f1;
        border-radius: 4rpx;
      }
      
      &::-webkit-scrollbar-thumb {
        background-color: #c1c1c1;
        border-radius: 4rpx;
        
        &:hover {
          background-color: #a8a8a8;
        }
      }
      
      code {
        font-family: 'Courier New', Consolas, monospace;
        font-size: 24rpx;
        color: #333333;
        line-height: 1.6;
        white-space: pre;
        word-wrap: normal;
        display: block;
        width: max-content;
        min-width: 100%;
        background-color: transparent;
        padding: 0;
      }
    }
    
    /* 行内代码样式 */
    code {
      background-color: #f0f0f0;
      color: #d63384;
      padding: 4rpx 8rpx;
      border-radius: 4rpx;
      font-family: 'Courier New', Consolas, monospace;
      font-size: 26rpx;
    }
    
    /* 强调文本样式 */
    strong {
      font-weight: 600;
      color: #333333;
    }
    
    /* 链接样式 */
    a {
      color: #00bdb4;
      text-decoration: none;
    }
    
    /* 列表样式 */
    ul, ol {
      margin: 20rpx 0;
      padding-left: 40rpx;
      
      li {
        margin-bottom: 10rpx;
        line-height: 1.6;
      }
    }
    
    /* 引用样式 */
    blockquote {
      background-color: #f8f8f8;
      border-left: 4rpx solid #00bdb4;
      padding: 20rpx;
      margin: 20rpx 0;
      border-radius: 0 8rpx 8rpx 0;
      
      p {
        margin-bottom: 0;
        color: #666666;
        font-style: italic;
      }
    }
  }
}

/* 错误状态 */
.error-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.error-image {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 40rpx;
}

.error-text {
  font-size: 28rpx;
  color: #999999;
  margin-bottom: 40rpx;
}

.retry-btn {
  background-color: #00bdb4;
  color: #ffffff;
  padding: 20rpx 40rpx;
  border-radius: 40rpx;
}

.retry-text {
  font-size: 28rpx;
  color: #ffffff;
}

/* 全局滚动条隐藏 */
::-webkit-scrollbar {
  display: none !important;
  width: 0 !important;
  height: 0 !important;
  background: transparent !important;
}

::-webkit-scrollbar-thumb {
  background: transparent !important;
}

::-webkit-scrollbar-track {
  background: transparent !important;
}
</style>

